package com.llt.user.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llt.common.core.domain.TableDataInfo;
import com.llt.common.core.utils.ThreadLocalUtil;
import com.llt.user.domain.exam.dto.ExamQueryDTO;
import com.llt.user.domain.exam.dto.ExamRankDTO;
import com.llt.user.domain.exam.vo.ExamRankVO;
import com.llt.user.domain.exam.vo.ExamVO;
import com.llt.user.domain.user.vo.UserVO;
import com.llt.user.manager.ExamCacheManager;
import com.llt.user.manager.UserCacheManager;
import com.llt.user.mapper.exam.ExamMapper;
import com.llt.user.mapper.user.UserExamMapper;
import com.llt.user.service.exam.IExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO dto) {
        // 1. 使用 PageHelper 进行分页查询
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return examMapper.selectExamList(dto);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO dto) {
        // 1. 从 redis 当中获取竞赛列表的数据
        Long total = examCacheManager.getListSize(dto.getType(), null);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            examVOList = list(dto);
            examCacheManager.refreshCache(dto.getType(), null);
        } else {
            examVOList = examCacheManager.getExamVOList(dto, null);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }

        // 过滤筛选的时间
        examVOList = filterTime(examVOList, dto.getStartTime(), dto.getEndTime());

        total = (long) examVOList.size();

        // 判断用户是否报名
        assembleExamVOList(examVOList);

        return TableDataInfo.success(examVOList, total);
    }

    @Override
    public String getFirstQuestion(Long examId) {
        checkAndRefresh(examId);
        return examCacheManager.getFirstQuestion(examId).toString();
    }

    @Override
    public String preQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.preQuestion(examId, questionId).toString();
    }

    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId, questionId).toString();
    }

    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examRankDTO.getPageNum(), examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
        }
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList, total);
    }

    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.getUserId();
        List<Long> userExamIdList = examCacheManager.getUserExamIdList(userId);
        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }

    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            // 缓存中存的 userId, 拿到昵称返回
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }

    private List<ExamVO> filterTime(List<ExamVO> examVOList ,String start, String end) {
        // 过滤筛选的时间
        if (start != null) {
            // 将 dto 中开始时间和结束时间转为 LocalDateTime 类型
            LocalDateTime startTime = stringTransferTime(start);
            // 删除查出来早于要求的exam
            examVOList.removeIf(examVO -> examVO.getStartTime().isBefore(startTime));
        }
        if (end != null) {
            // 将 dto 中开始时间和结束时间转为 LocalDateTime 类型
            LocalDateTime endTime = stringTransferTime(end);
            // 删除查出来晚于要求的exam
            examVOList.removeIf(examVO -> examVO.getEndTime().isAfter(endTime));
        }

        return examVOList;
    }

    private LocalDateTime stringTransferTime(String str) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(str, formatter);
    }

    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }
}
